import { _decorator, Node, Canvas, find } from 'cc';
import { Singleton } from '../utils/singleton';
import { Logger } from '../utils/logger';
import { BaseUI } from './base-ui';

/**
 * UI管理器
 * 负责管理所有UI组件的显示、隐藏和层级
 */
@Singleton
export class UIManager {
    /** 日志管理器 */
    private logger: Logger = new Logger();

    /** UI根节点 */
    private uiRoot: Node | null = null;

    /** UI组件映射表 */
    private uiMap: Map<string, BaseUI> = new Map();

    /**
     * 初始化UI管理器
     */
    public initialize(): void {
        this.logger.debug('[UIManager] Initializing');
        this.uiRoot = find('Canvas');
        if (!this.uiRoot) {
            this.logger.error('[UIManager] Canvas not found');
            return;
        }
    }

    /**
     * 显示UI组件
     * @param name 组件名称
     * @returns UI组件实例
     */
    public show<T extends BaseUI>(name: string): T | null {
        const ui = this.uiMap.get(name) as T;
        if (ui) {
            ui.show();
            return ui;
        }
        this.logger.warn(`[UIManager] UI component not found: ${name}`);
        return null;
    }

    /**
     * 隐藏UI组件
     * @param name 组件名称
     */
    public hide(name: string): void {
        const ui = this.uiMap.get(name);
        if (ui) {
            ui.hide();
        } else {
            this.logger.warn(`[UIManager] UI component not found: ${name}`);
        }
    }

    /**
     * 注册UI组件
     * @param name 组件名称
     * @param component UI组件实例
     */
    public register(name: string, component: BaseUI): void {
        if (this.uiMap.has(name)) {
            this.logger.warn(`[UIManager] UI component already exists: ${name}`);
            return;
        }
        this.uiMap.set(name, component);
        this.logger.debug(`[UIManager] Registered UI component: ${name}`);
    }

    /**
     * 注销UI组件
     * @param name 组件名称
     */
    public unregister(name: string): void {
        if (this.uiMap.has(name)) {
            this.uiMap.delete(name);
            this.logger.debug(`[UIManager] Unregistered UI component: ${name}`);
        }
    }

    /**
     * 获取UI组件
     * @param name 组件名称
     * @returns UI组件实例
     */
    public getUI<T extends BaseUI>(name: string): T | null {
        return this.uiMap.get(name) as T || null;
    }

    /**
     * 清理所有UI组件
     */
    public clear(): void {
        this.uiMap.clear();
        this.logger.debug('[UIManager] Cleared all UI components');
    }
} 